package com.pan.base;

import java.lang.reflect.Constructor;
import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * 用来反射的工具类
 */
public enum ReflectUtil {
    INSTANCE;
    public <T> T newInstance(String className){
        Class<T> targetClass = null;
        try {
            targetClass = (Class<T>) Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return classToObject(targetClass);
    }

    public  <T> T newInstanceAndCheck(String className, Class<T> genericInterface){
        Class<T> targetClass = null;
        try {
            targetClass = (Class<T>) Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        if (!Arrays.stream(targetClass.getGenericInterfaces())
                .filter(t->t.getTypeName().equals(genericInterface.getTypeName()))
                .findFirst().isEmpty())
            throw new RuntimeException("Type Error: "+className+" "+"is not "+ genericInterface.getTypeName());
        return classToObject(targetClass);
    }
    private <T> T classToObject(Class<T> targetClass){
        T result = null;
        try {
            Constructor<T> constructor = targetClass.getConstructor();
            result = constructor.newInstance();
        }catch (Exception e){
            throw new RuntimeException("Create Object Error: ", e);
        }
        return result;
    }
}
